import demjson
from flask import make_response, jsonify, request, app, Flask

from db import Session
from db.bidding import Menu

app = Flask(__name__)

@app.route("/api/v1/hello/ydsungan")
def hello():
    response = {"code": 200, "message": "hi, ydsungan", "data": 1}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response



@app.route("/api/v1/manjian/saveMenu",methods=["POST", "GET"])
def sign():
    data = request.values.get("menuList")
    data = demjson.decode(data)
    shopId = data.get("shopId")
    menuList = data.get("menuList")
    shopName = data.get("shopName")
    res = saveMenuList(shopId,shopName,menuList)
    if res:
        response = {"code": 200, "message": "保存成功", "data": 1}
    else:
        response = {"code": 500, "message": "保存失败", "data": 0}
    response = make_response(jsonify(response))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response

def saveMenuList(shopId,shopName,menuList):
    try:
        session = Session()
        sql = "delete from menu where shopId = '" + shopId + "';"
        session.execute(sql)
        for menu in menuList:
            session.add(
                Menu(
                    shopId = shopId,
                    shopName = shopName,
                    menu = menu.get("menu"),
                    outOfPacket = menu.get("outOfPacket"),
                    totalPackingFee = menu.get("totalPackingFee"),
                    totalPrice = menu.get("totalPrice")
                )
            )

        session.commit()
        session.close()
        return True
    except:
        return False


if __name__ == '__main__':
    app.run(host='0.0.0.0',port=3818)